package com.hliushi.learn.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.ResourceBundle;

/**
 * @author: yxzhang23
 * @time: 2021/3/16
 */
public class IpUtil2 {


    /**
     * unknown
     */
    private static final String UNKNOWN = "unknown";


    private static ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("application");

    // private static String AMAP_URL = "https://restapi.amap.com/v5/ip";
    private static String AMAP_URL;

    // private static String AMAP_KEY = "c8a775f116d1dec887c87e9af610c6d4";
    private static String AMAP_KEY;

    static {
        AMAP_URL = RESOURCE_BUNDLE.getString("amap.url");
        AMAP_KEY = RESOURCE_BUNDLE.getString("amap.key");
    }

    /**
     * 私有构造, 任何时候都不能实例化
     */
    private IpUtil2() {
    }

    /**
     * 获得国家
     */
    public static String getCountry(String ip) throws Exception {
        String content = httpDoGet(ip);
        JSONObject jsonObject = JSONObject.parseObject(content);
        return jsonObject.getString("country");
    }

    /**
     * 获得省份
     */
    public static String getProvince(String ip) throws Exception {
        String content = httpDoGet(ip);
        JSONObject jsonObject = JSONObject.parseObject(content);
        return jsonObject.getString("province");
    }

    /**
     * 获得城市
     */
    public static String getCity(String ip) throws Exception {
        String content = httpDoGet(ip);
        JSONObject jsonObject = JSONObject.parseObject(content);
        return jsonObject.getString("city");
    }


    /**
     * 发送get请求高德API, 根据ip获取到地址位置信息
     *
     * @param ip ip
     * @return 响应数据
     */
    private static String httpDoGet(String ip) throws Exception {
        StringBuilder builder = new StringBuilder();
        builder.append(AMAP_URL).append("?")
                .append("key=").append(AMAP_KEY).append("&")
                .append("type=4&")
                .append("ip=").append(ip);


        String url = builder.toString();
        HttpClientUtil.HttpClientResult clientResult = HttpClientUtil.doGet(url);
        return clientResult.getContent();
    }
}
